package com.lagou.serialize;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @AUTHOR: yb.feng
 * @DATE: 2020/5/26 20:19
 * @DESC:
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list) throws Exception {
        in.markReaderIndex();
        int dataLength = in.readInt();
        byte[] body = new byte[dataLength];
        in.readBytes(body);
        Object o = serializer.deserialize(clazz, body);
        list.add(o);
    }
}
